package zhieasy.cn.service.initiation.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import zhieasy.cn.common.utils.KeyUtil;
import zhieasy.cn.model.common.*;
import zhieasy.cn.model.initiation.AdminCollege;
import zhieasy.cn.model.initiation.StudentTask;
import zhieasy.cn.persistence.mapper.common.*;
import zhieasy.cn.persistence.mapper.initiation.AdminCollegeMapper;
import zhieasy.cn.persistence.mapper.initiation.StudentTaskMapper;
import zhieasy.cn.service.initiation.TeacherService;


import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sofency
 * @date 2020/8/12 23:42
 * @package IntelliJ IDEA
 * @description
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    CodeMapper codeMapper;

    @Autowired
    FreshmanIdMapper freshmanIdMapper;

    @Autowired
    StudentTaskMapper studentTaskMapper;

    @Autowired
    StudentUserMapper studentUserMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    CollegeInfoMapper collegeInfoMapper;

    @Autowired
    AdminCollegeMapper adminCollegeMapper;

    //获取学生到校情况
    @Override
    public Map<String,Object> getComeToSchoolDetails(String majorId) {
        Map<String,Object> result = new HashMap<>();//存储返回的结果

        AdminCollege adminColleges = getCurrentTeacher();
        if(Objects.isNull(adminColleges)){//说明没权限
            result.put("data","无权限访问");
        }else{//说明有权限
            String collegeId = adminColleges.getCollegeId();//获取collegeId
            if (StringUtils.isNullOrEmpty(majorId)) {
                return getInstitute(collegeId);
            } else {
                List<Grade> gradeList = getGradeList(majorId);//获取班级的信息
                List<Map<String,Object>> list = new ArrayList<>();
                gradeList.forEach(grade -> {
                    Map<String, Object> gradeDetail = getGradeDetail(grade.getGradeId());
                    list.add(gradeDetail);
                });
                result.put("data",list);
            }
        }
        return result;
    }

    //获取当前教师端登录的信息
    private AdminCollege getCurrentTeacher(){
        String openId = WechatUser.getWechatUserOpenIdFromSecurityContext();
        //调用老师
        Map<String,Object> map = new HashMap<>();
        map.put("open_id",openId);
        List<AdminCollege> adminColleges = adminCollegeMapper.selectByMap(map);
        if(CollectionUtils.isEmpty(adminColleges)) return null;
        return adminColleges.get(0);
    }
    //获取报名完成情况
    @Override
    public Map<String,Object> getSigned(String majorId){
        Map<String,Object> result = new HashMap<>();//存储返回的结果
        AdminCollege adminColleges = getCurrentTeacher();
        if(Objects.isNull(adminColleges)){
            result.put("data","无权限访问");
        }else{
            String collegeId = adminColleges.getCollegeId();
            if(StringUtils.isNullOrEmpty(majorId)){
                return getSignInstitute(collegeId);
            }else{
                List<Grade> gradeList = getGradeList(majorId);
                List<Map<String,Object>> list = new ArrayList<>();
                gradeList.forEach(grade -> {
                    Map<String, Object> gradeDetail = getSignGrade(grade.getGradeId());
                    list.add(gradeDetail);
                });
                result.put("data",list);
            }
        }
        return result;
    }

    //查询班级的总人数
    public List<FreshManId> getFreshManId(String gradeId){
        Map<String,Object> map = new HashMap<>();
        map.put("major_class",gradeId);
        List<FreshManId> freshManIds = freshmanIdMapper.selectByMap(map);
        return freshManIds;
    }
    /**
     * 获取到校的人数
     * @param gradeId
     * @param flag
     * @return
     */
    @Override
    public Map<String,Object> getStudentToSchool(String gradeId, Boolean flag) {
        List<FreshManId> freshManId = getFreshManId(gradeId);//班级所有人的信息
        List<StudentUser> users = getUsers(gradeId, false);//获取到校的人数
        List<String> ids = users.stream().map(studentUser -> studentUser.getOpenId()).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();

        List<FreshManId> in = freshManId.stream().filter(freshManId1 -> ids.contains(freshManId1.getOpenId())).
            collect(Collectors.toList());

        freshManId.removeAll(in);//剩下的人数
        if(flag){//在校的
            map.put("in", in.size());
            map.put("student",in);
        }else{
            map.put("out",freshManId.size());//剩下的大小
            map.put("student",freshManId);
        }
        return map;
    }

    @Override
    public StudentUser getStudentDetail() {
        String openId = WechatUser.getWechatUserOpenIdFromSecurityContext();
        StudentUser studentUser = studentUserMapper.selectById(openId);
        return studentUser;
    }

    @Override
    public Boolean loginByCode(String inviteCode) {
        String openId = WechatUser.getWechatUserOpenIdFromSecurityContext();//获取openId
        Map<String,Object> map = new HashMap<>(1,1);
        map.put("invite_code",inviteCode);
        List<Code> codes = codeMapper.selectByMap(map);

        //判断集合非空 非空进行注册
        if(!CollectionUtils.isEmpty(codes)){
            //邀请码的次数减一
            if(codes.get(0).getMaxNum()>codes.get(0).getUsedNum()){
                //更新剩余的个数
                codes.get(0).setUsedNum(codes.get(0).getUsedNum()+1);
                codeMapper.updateById(codes.get(0));

                //插入管理员的信息
                String collegeId = codes.get(0).getCollegeId();//获取collegeId
                AdminCollege adminCollege = new AdminCollege();
                adminCollege.setCollegeId(collegeId);
                adminCollege.setOpenId(openId);
                adminCollege.setPassword("null");
                adminCollege.setCreateTime(System.currentTimeMillis());
                adminCollege.setUpdateTime(System.currentTimeMillis());
                adminCollege.setIsDelete(0);
                adminCollege.setUniteId(KeyUtil.genUniqueKey());
                adminCollegeMapper.insert(adminCollege);
                return true;
            }
        }
        return false;
    }

    //获取专业下对应的班级
    public List<Grade> getGradeList(String majorId){
        Map<String,Object> map = new HashMap<>();
        map.put("major_id",majorId);
        List<Grade> grades = gradeMapper.selectByMap(map);
        return grades;
    }
    //获取报名成功的班级
    private Map<String,Object> getSignGrade(String id){
        List<StudentUser> users = getUsersList(id,false);
        //筛选出学院的
        Grade grade = getGradeInfo(id);
        Map<String,Object> result = new HashMap<>();
        if(users==null||users.size()==0){
            result.put("signed",0);
        }else{
            result.put("signed",users.size());
        }
        result.put("grade",grade);
        return result;
    }

    //flag 为true 查询的是学院的信息  为false查询的是专业的信息


    //获取学院的报名情况
    private Map<String,Object> getSignInstitute(String collegeId){
        List<StudentUser> users = getUsersList(collegeId,true);
        //筛选出学院的
        CollegeInfo collegeInfo =  getInstituteNum(collegeId);
        Map<String,Object> result = new HashMap<>();
        if(users==null||users.size()==0){
            result.put("signed",0);
        }else{
            result.put("signed",users.size());
        }
        result.put("college",collegeInfo);
        return result;
    }



    //查询查询同班到校的情况
    //flag为true 表示查询的是学院  为false查询的是班级
    private List<StudentUser> getUsers(String id, boolean flag){
        QueryWrapper<StudentTask> wrapper = new QueryWrapper<>();
        wrapper.select("distinct open_id");
        List<StudentTask> list = studentTaskMapper.selectList(wrapper);
        List<String> ids = list.stream().map(StudentTask::getOpenId).collect(Collectors.toList());//获取完成任务的ids即到校的人数
        if(ids.size() == 0) return null;
        Map<String,Object> map = new HashMap<>();
        if(flag){
            map.put("student_college",id);
        }else{
            map.put("student_grade",id);
        }
        return studentUserMapper.selectByMap(map);
    }

    //查询同伴任务完成情况
    private List<StudentUser> getUsersList(String id,boolean flag){
        Map<String,Object> map = new HashMap<>();
        map.put("finish_task",1);//完成的任务列表  每个学生之后一个完成的情况
        List<StudentTask> studentTasks = studentTaskMapper.selectByMap(map);
        List<String> ids = new ArrayList<>();
        if(!CollectionUtils.isEmpty(studentTasks)){
            ids = studentTasks.stream().map(studentTask -> studentTask.getOpenId()).distinct().collect(Collectors.toList());;
        }
        Map<String,Object> college = new HashMap<>();
        if(flag){
            college.put("student_college",id);
        }else{
            college.put("student_grade",id);
        }

        //过滤掉不在完成任务的队列中
        List<StudentUser> users  = studentUserMapper.selectByMap(college);
        List<String> finalIds = ids;
        List<StudentUser> collect = users.stream().filter(user -> finalIds.contains(user.getOpenId())).collect(Collectors.toList());
        return collect;
    }

    //获取学院到校情况
    private Map<String,Object>  getInstitute(String collegeId){
        //获取学院下当前到校的人的信息
        List<StudentUser> users = getUsers(collegeId,true);
        CollegeInfo collegeInfo = getInstituteNum(collegeId);//获取学院当前的信息
        Map<String,Object> result = new HashMap<>();
        if(users==null){
            result.put("in",0);
        }else{
            //根据所有用户的信息表筛选出老师学院的信息
            result.put("in",users.size());
        }
        result.put("college",collegeInfo);
        return result;
    }

    //获取班级到校情况
    private Map<String,Object> getGradeDetail(String gradeId){
        //查询新生的表
        Map<String,Object> map = new HashMap<>();
        map.put("major_class",gradeId);
        //首先获取所有的任务步骤表
        Map<String,Object> result = new HashMap<>();
        Grade grade = getGradeInfo(gradeId);//获取班级的信息
        List<StudentUser> users  = getUsers(gradeId,false);//获取班级到校的人数
        if(users==null){
            result.put("in",0);
        }else{
            result.put("in",users.size());
        }
        result.put("grade",grade);
        return result;
    }

    //获取学院的人数
    private CollegeInfo getInstituteNum(String collegeId){
        Map<String,Object> map  = new HashMap<>();
        //查询学院总人数
        map.put("college_id",collegeId);
        List<CollegeInfo> collegeInfos = collegeInfoMapper.selectByMap(map);
        return collegeInfos.get(0);
    }


    //获取班级信息
    private Grade getGradeInfo(String gradeId){
        Map<String,Object> map = new HashMap<>();
        map.put("grade_id",gradeId);
        List<Grade> grades = gradeMapper.selectByMap(map);//查询出唯一的一个
        return grades.get(0);
    }
}
